# -*- coding: utf-8 -*-
import sys

reload(sys)
#print sys.getdefaultencoding()
sys.setdefaultencoding('utf8')

from numpy import *
import operator
from os import listdir

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']
    return group, labels




def classfy_kNN(inX, dataSet, labels, k):
    """

    :param inX:  node X to be classfied
    :param dataSet:  traing data set
    :param labels:  traning data label
    :param k:  k nearest node
    :return:
    """

    #distance calucation
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX,(dataSetSize,1)) - dataSet
    sqDiffMat = diffMat**2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances**.5
    sortedDistIndicies = distances.argsort()

    #voting with lowest k distance
    classCount = {}
    for i in range(k) :
        voteLabel = labels[sortedDistIndicies[i]]
        classCount[voteLabel] = classCount.get(voteLabel,0) +1

    #sort dictionary
    # key=operator.itemgetter(1)的意思是按照字典里的第一个排序，{A:1,B:2},要按照第1个（AB是第0个），即‘1’‘2’排序。
    # reverse=True是降序排序
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


def file2matrix(filename):
    """
    read data from txt file and load them into numpy matrix
    :param filename:
    :return:
    """
    love_dictionary = {'largeDoses': 3, 'smallDoses': 2, 'didntLike': 1}
    fr = open(filename)
    lines = fr.readlines( )
    numberOfLines = len(lines)
    numberOfColumns = len(lines[0].strip().split('\t'))
    returnMat = zeros((numberOfLines,numberOfColumns-1))  #create numberOfLinesX3 matrix with all value as zeros
    classLabelVector = []
    index = 0
    # for line in lines:
    #     line = line.strip()
    #     listFromLine = line.split('\t')
    #     returnMat[index, :] = listFromLine[0:numberOfColumns-1]
    #     # classLabelVector.append(int(listFromLine[-1]))
    #     classLabelVector.append( listFromLine[-1]  )
    #     index += 1
    for line in lines:
        line = line.strip( )
        listFromLine = line.split( '\t' )
        returnMat[index, :] = listFromLine[0:3]
        if (listFromLine[-1].isdigit( )):
            classLabelVector.append( int( listFromLine[-1] ) )
        else:
            classLabelVector.append( love_dictionary.get( listFromLine[-1] ) )
        index += 1
    return returnMat, classLabelVector


def autoNorm(dataSet):
    minVals = dataSet.min(0)  #The 0 in dataSet.min(0) allows you to take the minimums from the columns,\
    #  not the rows.
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = dataSet - tile(minVals, (m,1))  #NumPy tile() function to create a matrix the same size \
    # as our input matrix and then fill it up with many copies, or tiles.
    normDataSet = normDataSet / tile(ranges,(m,1))  #subtract the minimum values and then divide by the range.
    return normDataSet, ranges, minVals



def datingClassTest():
    hoRatio = 0.10
    datingDataMat, datingLabels = file2matrix( "datingTestSet.txt" )

    # normal
    normMat, ranges, minVals = autoNorm( datingDataMat )
    m = normMat.shape[0]
    numTestVecs = int( m * hoRatio )
    errorCount = 0.0
    for i in range(numTestVecs):
        classifierResult = classfy_kNN(normMat[i,:], normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],10)
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])

        if (classifierResult != datingLabels[i]):
            errorCount += 1.0

    print "the total error rate is: %f" % (errorCount/float(numTestVecs))



def classifyPerson():
    resultList = ['not at all','in small doses', 'in large doses']
    percentTats = float(raw_input("percentage of time spent playing video games?"))  #function raw_input(). \
    # This gives the user a text prompt and returns whatever the user enters.
    ffMiles = float(raw_input("frequent flier miles earned per year?"))
    iceCream = float(raw_input("liters of ice cream consumed per year?"))
    datingDataMat,datingLabels = file2matrix('datingTestSet.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    inArr = array([ffMiles, percentTats, iceCream])
    classifierResult = classfy_kNN((inArr-minVals)/ranges,normMat,datingLabels,3)
    print "You will probably like this person: ", resultList[classifierResult - 1]


def img2vector(filename):
    """
    read 32X32 matrix to a 1X1024 vector
    :param filename:
    :return:
    """
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect

def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir('digits/trainingDigits')           #load the training set
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vector('digits/trainingDigits/%s' % fileNameStr)
    testFileList = listdir('digits/testDigits')        #iterate through the test set
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('digits/testDigits/%s' % fileNameStr)
        classifierResult = classfy_kNN(vectorUnderTest, trainingMat, hwLabels, 3)
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)
        if (classifierResult != classNumStr): errorCount += 1.0

    print "\nthe total number of errors is: %d" % errorCount
    print "\nthe total error rate is: %f" % (errorCount/float(mTest))



handwritingClassTest()
datingClassTest()



# group,labels = createDataSet()
# cnt = classfy_kNN([0,0], group, labels, 3)
# print cnt







datingDataMat,datingLabels = file2matrix("datingTestSet.txt")
# print returnMat[0:10]
# print classLabelVector[0:10]
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
# ax.scatter(datingDataMat[:,1], datingDataMat[:,2])
# ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 10.0*array(datingLabels), 20.0*array(datingLabels))
ax.scatter(datingDataMat[:,0], datingDataMat[:,1], 10.0*array(datingLabels), 20.0*array(datingLabels))
# ax.scatter(datingDataMat[:,1], datingDataMat[:,2],15.0*array(datingLabels).astype(float), 15.0*array(datingLabels).astype(float))
plt.show()

#normal
normMat, ranges, minVals = autoNorm(datingDataMat)

print "Stop here"


